/*
 * 功能: 工具类变量及对象定义
 * 避免整个系统中多处使用同一个工具类对象时，每次都定义一个新的相同对象
 * 一旦发现定义有误，导致整个项目的所有涉及的代码都要更改的强耦合关系
 *
 * 定义举例：
 * 各页面表单通用的正则表达式、工具方法等
 *
 * 要求与用法：
 * 1、不允许在组件或js中单独定义通用的工具类变量，方法
 * 2、vue组件中以this.$ui.propName的形式访问工具类定义，js代码中直接引入该文件即可
 * http://192.168.102.233:83/#/doc/guid/utils
 */
import axios from 'axios'

export const pattern = {
  phone: /^1[3456789]\d{9}$/,
  chinese: /^[\u0391-\uFFE5]+$/,
  email: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
  idCardNo: /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
  urlFull: /(^((https|ftp|http|file):))((\/\/)|www\.)*([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/gm
}
// /(http|https):\/\/([\w.]+\/?)\S*/

export function convert2FullPath (localPath) {
  if (localPath && localPath.startsWith('/PRIVATE')) {
    return `${window.$app.fileBaseUrl}${localPath}`
  }
  return `${window.$app.filePublicSever}${localPath}`
}
/**
* 功能: 转换视频的封面地址
*  @param {String} url 文件路径
*/
export function getVideoCover (url) {
  if (url && url.length !== 0) {
    return url.substring(0, url.lastIndexOf('.')) + '.jpeg'
  }
  return url
}
export function getResourcePrefix (localPath) {
  return localPath.startsWith('/PRIVATE') ? window.$app.fileBaseUrl : window.$app.filePublicSever
}

export function getMediaPrefix (localPath) {
  if (localPath) {
    return localPath.startsWith('/PRIVATE') ? window.$app.gateway : window.$app.publicGateway
  }
  return window.$app.publicGateway
}

/**
 * 开启定时器
 * @param {*} key
 * @param {*} call
 * @param {*} timer
 */
export function startSetInterval (key, call, timer) {
  window.interval = window.interval ? window.interval : {}
  if (window.interval[key]) window.clearInterval(window.interval[key])
  window.interval[key] = window.setInterval(() => {
    if (call) call()
    else {
      window.clearInterval(window.interval[key])
    }
  }, timer || 10000)
}

/**
 * 关闭定时器
 * @param {*} key
 * @param {*} call
 */
export function endSetInterval (key) {
  window.interval = window.interval ? window.interval : {}
  if (window.interval[key]) {
    window.clearInterval(window.interval[key])
  }
}
/**
 *功能：获取唯一标识
*/
export function getIndentity () {
  function S4 () {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
  }
  return (
    S4() +
    S4() +
    '-' +
    S4() +
    '-' +
    S4() +
    '-' +
    S4() +
    '-' +
    S4() +
    S4() +
    S4()
  )
}

/**
 * 功能：手机横屏
 */
export function toHscreen () {
  if (window.$app.appType === 'mobile' || window.$app.appType === 'pad') {
    if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.changeOrientation) {
      window.creativeJSCallbackForOther.changeOrientation('', '1')
    } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.xblChangeOrientation) {
      window.webkit.messageHandlers.xblChangeOrientation.postMessage({ orientation: '1' })
    }
  }
}

/**
* 功能：手机坚屏
*/
export function toVscreen () {
  if (window.$app.appType === 'mobile' || window.$app.appType === 'pad') {
    if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.changeOrientation) {
      window.creativeJSCallbackForOther.changeOrientation('', '0')
    } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.xblChangeOrientation) {
      window.webkit.messageHandlers.xblChangeOrientation.postMessage({ orientation: '0' })
    }
  }
}

/**
* 功能：pad返回校比邻 (不清除密码)
*/
export function backToPadXBLLogin () {
  if (window.$app.appType === 'pad') {
    if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.padLoginOut) {
      window.creativeJSCallbackForOther.padLoginOut()
    } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.xblPadLoginOut) {
      window.webkit.messageHandlers.xblPadLoginOut.postMessage({})
    }
  }
}

/**
* 功能：pad返回校比邻（清除密码）
*/
export function backToPadXBLClearPasswordLogin () {
  if (window.$app.appType === 'pad') {
    if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.padLoginOutClearPwd) {
      window.creativeJSCallbackForOther.padLoginOutClearPwd()
    } else if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.padLoginOut) {
      // 没有新方法 使用老方法
      window.creativeJSCallbackForOther.padLoginOut()
    } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.xblPadLoginOut) {
      window.webkit.messageHandlers.xblPadLoginOut.postMessage({})
    }
  }
}

/**
* 功能：返回校比邻
*/
export function backToXBL () {
  if (window.$app.appType === 'mobile' || window.$app.appType === 'pad') {
    if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.xbl_goback) {
      window.creativeJSCallbackForOther.xbl_goback()
    } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.xblGoback) {
      window.webkit.messageHandlers.xblGoback.postMessage({})
    }
  }
}

/**
* 功能：是否未教师
*/
export function checkUserIsTeacher () {
  const roleIds = window.$app.user.roleId && window.$app.user.roleId.split(',')
  if (roleIds && roleIds.length > 0) {
    for (let index = 0; index < roleIds.length; index++) {
      const roleId = roleIds[index]
      if (roleId === '1000000002') {
        return true
      }
    }
  }
  return false
}

// 获取壳子是校比邻还是ai课堂
export function getCurrentFlavor () {
  if (window.$app.appType === 'pad') {
    if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.getCurrentFlavor) {
      window.creativeJSCallbackForOther.getCurrentFlavor()
    } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.getCurrentFlavor) {

    }
  }
}

/**
* 功能：开启扫码
*/
export function qRCodeScan () {
  if (window.$app.appType === 'mobile' || window.$app.appType === 'pad') {
    if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.qRCodeScan) {
      window.creativeJSCallbackForOther.qRCodeScan('')
    } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.xblQRCodeScan) {
      window.webkit.messageHandlers.xblQRCodeScan.postMessage(null)
    }
  }
}

/**
 * 开启直播
 * @param {*} liveInfo
 */
export function openLivePlayer (liveInfo) {
  liveInfo.player.dragable = '1'
  liveInfo = JSON.stringify(liveInfo)
  try {
    if (window.$app.appType === 'mobile' || window.$app.appType === 'pad') {
      if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.openLiveWithYunxin) {
        // alert('开始调用校比邻播放器')
        window.creativeJSCallbackForOther.openLiveWithYunxin(liveInfo, '1')
      } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.xblOpenLiveWithYunxin) {
        // alert('开始调用ios播放器')
        window.webkit.messageHandlers.xblOpenLiveWithYunxin.postMessage({ liveInfo })
      } else {
        window.$ui.msg('环境不支持，请下载最新校比邻或客户端上课吧~')
      }
    } else if (window.$app.appType === 'pad') {
      // window.android.stopRecord();
      if (window.android.openLiveWithYunxin && window.android) {
        window.android.openLiveWithYunxin(liveInfo)
      }
    }
  } catch {

  }
}

export function closeLivePlayer () {
  if (window.$app.appType === 'mobile' || window.$app.appType === 'pad') {
    if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.closeLiveWithYunxin) {
      window.creativeJSCallbackForOther.closeLiveWithYunxin('')
    } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.xblCloseLiveWithYunxin) {
      window.webkit.messageHandlers.xblCloseLiveWithYunxin.postMessage({})
    }
  }
}

/**
* 功能：显示直播窗口
*/
export function showLivePlayer () {
  // alert('显示直播')
  if (window.$app.appType === 'mobile' || window.$app.appType === 'pad') {
    if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.showLivePlayerWithYunxin) {
      window.creativeJSCallbackForOther.showLivePlayerWithYunxin('')
    } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.xblShowLivePlayerWithYunxin) {
      window.webkit.messageHandlers.xblShowLivePlayerWithYunxin.postMessage({})
    }
  }
}

/**
* 功能：隐藏直播窗口
*/
export function hideLivePlayer () {
  // alert('功能：隐藏直播窗口')
  if (window.$app.appType === 'mobile' || window.$app.appType === 'pad') {
    if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.hideLivePlayerWithYunxin) {
      window.creativeJSCallbackForOther.hideLivePlayerWithYunxin('')
    } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.xblHideLivePlayerWithYunxin) {
      window.webkit.messageHandlers.xblHideLivePlayerWithYunxin.postMessage({})
    }
  }
}

/**
 *  功能：屏幕广播
 * @returns
 */
export function broadcast () {
  window.broadcast = window.broadcast || {}
  const that = {}
  /**
   * 功能： 开启屏幕广播
   * @param {*} userId
   * @param {*} ip
   * @param {*} port
   */
  that.startRemoteDesk = (userId, ip, port) => {
    if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.startRemoteDesk) {
      window.broadcast.ip = ip || window.broadcast.ip
      window.broadcast.port = port || window.broadcast.port
      // alert(JSON.stringify({ ip: window.broadcast.ip, port: window.broadcast.port, userId, userId }))
      // window.webkit.messageHandlers.startRemoteDesk.postMessage({ ip: window.broadcast.ip, port: window.broadcast.port, userId: userId })
      if (!window.broadcast.ip || !window.broadcast.port) return
      window.creativeJSCallbackForOther.startRemoteDesk(`${window.broadcast.ip}`, parseInt(window.broadcast.port), `${userId}`)
    } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.startRemoteDesk) {
      window.webkit.messageHandlers.startRemoteDesk.postMessage({ ip, port, userId })
    }
  }

  /**
   * 功能：结束屏幕广播
   */
  that.endRemoteDesk = () => {
    // if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.endRemoteDesk) {
    //   window.webkit.messageHandlers.endRemoteDesk.postMessage({})
    // }
    if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.endRemoteDesk) {
      window.creativeJSCallbackForOther.endRemoteDesk()

      // window.location.reload()
    } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.endRemoteDesk) {
      window.webkit.messageHandlers.endRemoteDesk.postMessage({})
    }
  }

  /**
   * 功能：清楚本地存储的Ip和端口
   */
  that.clearIpPort = () => {
    window.broadcast = {}
  }

  return that
}

/**
 * 设置投影
 */
export function setRemoteProjectIp (ip, port) {
  if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.setRemoteProjectIp) {
    window.creativeJSCallbackForOther.setRemoteProjectIp(ip, port)
  }
}

/**
 * 开始pad投影屏 --pad端方法
 */
export function StartPadScreenProject (ip, port, userId, position = 0) {
  if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.startScreenProject) {
    window.creativeJSCallbackForOther.startScreenProject(ip, port, userId, position)
  } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.xblStartScreenProject) {
    window.webkit.messageHandlers.xblStartScreenProject.postMessage({ ip, port, userId, position })
  }
}

/**
 * 结束pad投影屏 --pad端方法
 */
export function endPadScreenProject () {
  if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.endScreenProject) {
    window.creativeJSCallbackForOther.endScreenProject()
  } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.xblEndScreenProject) {
    window.webkit.messageHandlers.xblEndScreenProject.postMessage({})
  }
}

/**
   * 功能：获取跳转到Ai测评指定页面的url地址
   * @param {String} path Ai测评的路由页路径
   * @param {Object} params 要带到路由页中的查询参数
   * @param {String} appName 跳到哪个系统，默认为exam，可选值为
   * @param {boolean} showPadBackUrl 是否需要带返回课堂的参数
   *  |— webIndex-web端首页 mobileIndex-移动端首页
   *  |— exam-考试中心 homework-作业中心 question-题库中心
   *  |— homeworkMobile-移动端AI作业 wrongQuestionSet-移动端错题本
   */
export function getAiTestUrl (path, params, appName = 'exam', showPadBackUrl = false, otherParams = null) {
  const token = window.$app.user.token
  const userInfo = window.$app.user

  return axios.post(`${window.$app.ecoGateway}/openapi-uc/accreditcode/getAccreditCode`, {
    accessToken: window.$app.user.token,
    userId: window.$app.userId
  }).then(({ data }) => {
    let accreditCode = data.responseEntity.accreditCode
    if (accreditCode) {
      if (!window.$ui.cookie.get('ai_exam_cache_cleared')) {
        // 清空测评用户认证保存在cookie中的值
        window.$ui.cookie.delete('webauthorized')
        // 清空测评缓存的用户信息
        window.localStorage.removeItem('$user')
        // 指定第三个参数为0，使cookie的生存期为浏览器打开的会话周期(只要有一个tab页在，浏览器会话就会保持)，浏览器只要关闭(最后一个tab页也被关闭，即浏览器从进程中完全删除）该cookie就会失效
        window.$ui.cookie.set('ai_exam_cache_cleared', 'true', 0)
      }

      let clientType = 1
      if (window.$app.appType === 'pad') clientType = 2

      let aiTestUrl = `${window.$app.aiTest[appName]}/login?accredit_code=${accreditCode}&token=${token}&userId=${userInfo.userId}&isFromClass=1&appType=${window.$app.appType}&client_type=${clientType}`

      if (showPadBackUrl) {
        let path = ''
        if (userInfo) {
          const roleId = userInfo.roleId
          if (roleId.indexOf('1000000003') !== -1) {
            path = window.$app.aiClass.student + '/pad-index'
            // path = window.$app.aiClassC15Url + 'student/padindex'
          }
          if (roleId.indexOf('1000000002') !== -1) {
            path = window.$app.aiClass.teacher + '/pad-index'
          }
        }
        aiTestUrl = `${aiTestUrl}&href=${encodeURIComponent(path)}`
      }

      if (path) {
        aiTestUrl += `&to=${encodeURIComponent(path + '?' + window.$ui.qs.stringify(params))}`
      }

      if (otherParams) {
        aiTestUrl += `${otherParams}`
      }
      // 解决缓存问题
      aiTestUrl += `&date=${new Date().getTime()}`

      return aiTestUrl
    } else {
      return new Error('failed to get the acredit code.')
    }
  })
}

/**
   * 功能：获取跳转到Ai测评指定页面的url地址
   * @param {String} path Ai测评的路由页路径
   * @param {Object} params 要带到路由页中的查询参数
   * @param {String} appName 跳到哪个系统，默认为exam，可选值为
   * @param {boolean} showPadBackUrl 是否需要带返回课堂的参数
   *  |— webIndex-web端首页 mobileIndex-移动端首页
   *  |— exam-考试中心 homework-作业中心 question-题库中心
   *  |— homeworkMobile-移动端AI作业 wrongQuestionSet-移动端错题本
   */
export function getAiTestUrlFormXbl (path, params, appName = 'homeworkMobile', backUrl = '') {
  const token = window.$app.user.token
  const userInfo = window.$app.user

  return axios.post(`${window.$app.ecoGateway}/openapi-uc/accreditcode/getAccreditCode`, {
    accessToken: window.$app.user.token,
    userId: window.$app.userId
  }).then(({ data }) => {
    let accreditCode = data.responseEntity.accreditCode
    if (accreditCode) {
      let aiTestUrl = `${window.$app.aiTest[appName]}/login?accredit_code=${accreditCode}&token=${token}&userId=${userInfo.userId}&fromGzh=1&toParams=${encodeURIComponent(JSON.stringify(params))}`

      // let aiTestUrl = `http://192.168.112.115:8080/mobile/ai-homework-mobile.html#/login?accredit_code=${accreditCode}&token=${token}&userId=${userInfo.userId}&fromGzh=1&toParams=${encodeURIComponent(JSON.stringify(params))}`

      if (backUrl) {
        aiTestUrl = `${aiTestUrl}&href=${encodeURIComponent(backUrl)}`
      }

      if (path) {
        aiTestUrl += `&to=${path}`
        // aiTestUrl += `&to=${path}?${encodeURIComponent(window.$ui.qs.stringify(params))}`
      }

      return aiTestUrl
    } else {
      return new Error('failed to get the acredit code.')
    }
  })
}

/**
  * 功能：判断设备类型
  */
export function getTerminal () {
  let map = { 'pad': 2, 'web': 1, 'pc': 3 }
  let key = window.$app.appType
  return map[key]
}

/**
   * 功能：判断一个值是否为空值
   * @param {*} val 需要判断的值
   */
export function isEmptyValue (val) {
  if (Array.isArray(val)) {
    return val.length === 0
  } else {
    return [null, undefined, ''].includes(val)
  }
}

/**
   * 视频拍摄
   * @param {*} hdMode
   */
export function setTakeVideoHdMode (hdMode) {
  if (window.$app.appType === 'mobile' || window.$app.appType === 'pad') {
    // 安卓
    if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.setTakeVideoHdMode) {
      window.creativeJSCallbackForOther.setTakeVideoHdMode(hdMode)
    } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.xblSetTakeVideoHdMode) {
      window.webkit.messageHandlers.xblSetTakeVideoHdMode.postMessage({ hdMode: hdMode })
    }
  }
}

/**
   * 设置AI课堂input上传方式接受类型，多个类型使用英文逗号分隔。如：.png,.mp4
   * @param acceptTypes
   * @param number
   * 注：此接口必须在需要使用input传值时，且在调用input前调用，设置的值3秒内有效。
   * 由于android webview兼容性原因，js那边在setTimeout来调用原生input没反应，所以需要用此方式传值
   */
export function setHDInputAcceptTypes (acceptTypes, number) {
  if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.setHDInputAcceptTypes) {
    if (!number) {
      window.creativeJSCallbackForOther.setHDInputAcceptTypes(acceptTypes || '')
    } else {
      window.creativeJSCallbackForOther.setHDInputAcceptTypesWithCount(acceptTypes || '', number)
    }
  } else if (window.webkit && window.webkit.messageHandlers) {

  }
}
/**
   * 功能：将base64图片转换为 blob
   */
export function dataURLtoBlob (dataurl) {
  var arr = dataurl.split(','); var mime = arr[0].match(/:(.*?);/)[1]
  var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}
/**
   * 功能：将blob转换为base 64
   * @param {*} blob
   * @param {*} callback
   */
export function blobToDataURL (blob, callback) {
  let a = new FileReader()
  a.onload = function (e) { callback(e.target.result) }
  a.readAsDataURL(blob)
}
/**
   * 功能：将图片读取为base64
   * @param {图片地址} src
   */
export function dataURLtoBase64 (src, outputFormat) {
  // 传入图片路径，返回base64
  if (!src) return Promise.reject(new Error('请传入图片地址...'))
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest()
    xhr.open('POST', src, true)
    xhr.responseType = 'arraybuffer'
    xhr.onload = function (e) {
      if (xhr.status === 200) {
        var uInt8Array = new Uint8Array(xhr.response)
        var i = uInt8Array.length
        var binaryString = new Array(i)
        while (i--) {
          binaryString[i] = String.fromCharCode(uInt8Array[i])
        }
        var data = binaryString.join('')
        var base64 = window.btoa(data)
        var dataUrl = 'data:' + (outputFormat || 'image/png') + ';base64,' + base64
        resolve(dataUrl)
      }
    }
    xhr.send()
  })
}

/**
   * AI课堂录音调用
   * @param actionType：操作类型：1-开始录音，2-暂停录音，3-恢复录音，4-停止录音，5-取消录制
   * @return 对应传类型1(或者input方式传.vrocstart)启动录音时，原生会调用js方法 StartResult告诉H5启动录音是否正常（
   * 值为：1-启动录音失败（权限异常），2-启动录音异常，3-启动录音成功），H5只有拿到3值时才认为开始录音了
   *
   * 注：此处传4会停止录音释放资源，并通过input方式将文件地址回传给H5
   */
export function hdVoiceRecorder (actionType) {
  // if (window.$app.appType === 'pad') {
  if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.hdVoiceRecorder) {
    window.creativeJSCallbackForOther.hdVoiceRecorder(`${actionType}`)
  } else if (window.webkit && window.webkit.messageHandlers) {
    if (actionType === 1) {
      // 开始
      window.webkit.messageHandlers.xblAudioStartRecord.postMessage({})
    } else if (actionType === 2) {
      // 暂停
      window.webkit.messageHandlers.xblAudioPauseRecord.postMessage({})
    } else if (actionType === 3) {
      // 恢复
      window.webkit.messageHandlers.xblAudioStartRecord.postMessage({ openType: '1' })
    } else if (actionType === 4) {
      // 停止
      window.webkit.messageHandlers.xblAudioStopRecord.postMessage({})
    }
  }
  // }
}

/**
 * AI课堂存储到本地
 * @param base64Code-base64图片 必传
 * @param saveDirPath-保存路径 必传 可以是空值
 * @param fileName-文件名 必传 可以是空值
 */
export function saveWriteBoardPicture (base64Code = '', saveDirPath = '', fileName = '') {
  if (window.$app.appType === 'pad') {
    if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.saveWriteBoardPicture) {
      window.creativeJSCallbackForOther.saveWriteBoardPicture(base64Code, saveDirPath, fileName)
    } else if (window.webkit && window.webkit.messageHandlers) {
      window.webkit.messageHandlers.saveWriteBoardPicture.postMessage(base64Code, saveDirPath, fileName)
    }
  }
}

/**
 * AI课堂PAD端 将pad端的缓存文件保存到目标目录
 * @param destDirPath-目标路径 必传 可以是空值
 * @param fileName-文件名 必传 可以是空值
 */
export function changeCacheFilePath (destDirPath = '', fileName = '') {
  if (window.$app.appType === 'pad') {
    if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.changeCacheFilePath) {
      window.creativeJSCallbackForOther.changeCacheFilePath(destDirPath, fileName)
    } else if (window.webkit && window.webkit.messageHandlers) {
      window.webkit.messageHandlers.changeCacheFilePath.postMessage(destDirPath, fileName)
    }
  }
}

/**
 * PAD 锁屏
 */
export function disableSysNavgTools () {
  if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.disableSysNavgTools) {
    window.creativeJSCallbackForOther.disableSysNavgTools()
  } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.xblDisableSysNavgTools) {

  }
}

/**
 * PAD 解锁屏幕
 */
export function enableSysNavgTools () {
  if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.enableSysNavgTools) {
    window.creativeJSCallbackForOther.enableSysNavgTools()
  } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.xblDisableSysNavgTools) {

  }
}

export function getBase64ByUrl (src, callback, outputFormat) {
  var xhr = new XMLHttpRequest()
  xhr.open('POST', src, true)
  xhr.responseType = 'arraybuffer'

  xhr.onload = function (e) {
    // eslint-disable-next-line
    if (xhr.status == 200) {
      var uInt8Array = new Uint8Array(xhr.response)
      var i = uInt8Array.length
      var binaryString = new Array(i)
      while (i--) {
        binaryString[i] = String.fromCharCode(uInt8Array[i])
      }
      var data = binaryString.join('')
      var base64 = window.btoa(data)
      var dataUrl = 'data:' + (outputFormat || 'image/png') + ';base64,' + base64
      if (callback) callback(dataUrl)
    }
  }

  xhr.send()
}

export function getBase64Image (img, width, height) {
  var canvas = document.createElement('canvas')
  canvas.width = width || img.width
  canvas.height = height || img.height

  var ctx = canvas.getContext('2d')
  ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
  var dataURL = canvas.toDataURL('image/jpeg', 0.5)
  canvas = null
  return dataURL
}

/**
 * 功能：将图片读取为base64
 * @param {图片地址} img
 */
export function getBase64 (img) { // 传入图片路径，返回base64
  if (!img) return new Promise(function (resolve, reject) { resolve() })
  try {
    return new Promise(function (resolve, reject) {
      try {
        getBase64ByUrl(img, resolve)
      } catch (e) {
        reject(e)
      }
    })
  } catch (e) {
    return new Promise(function (resolve, reject) { resolve() })
  }
}

/**
 * 开始截屏
 */
export function ScreenCaptureByParams () {
  if (window.$app.appType === 'mobile' || window.$app.appType === 'pad') {
    if (window.creativeJSCallbackForOther && window.creativeJSCallbackForOther.screenShot) {
      window.creativeJSCallbackForOther.screenShot(0, 0, 0, 0)
    } else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.xblScreenShot) {
      window.webkit.messageHandlers.xblScreenShot.postMessage({})
    }
  }
}

/**
  * 功能：通过路径的文件后缀格式给文件名添加后缀(因文件名没有后缀下载可能会变成xml)
  *  @param {String} url 文件路径
  *  @param {String} fileName 文件路径
  *  @returns {String} fileName 返回新的文件名
*/
export function getFileNameByUrl (url, fileName) {
  let num = url.lastIndexOf('.')
  let ext = url.substring(num)
  let reg = new RegExp('(.*)' + url.substring(num))
  let name = ''
  if (fileName && fileName.lastIndexOf(ext) >= 0) {
    name = fileName.replace(reg, '$1') // 有后缀？匹配最后一个mp4后缀的文件名 替换掉
  } else {
    name = fileName
  }
  return ext === '.html' ? name + '.zhtml' : name + ext
}
export function checkUserIsStudent () {
  const roleIdList = window.$app.user.roleIdList
  return roleIdList.includes('1000000003')
}
/**
  * 功能：文档转换参数加密
*/
export function getTransferKey () {
  let CryptoJS = window.$ui.CryptoJS
  let key = CryptoJS.enc.Utf8.parse('d5d8s145e6705e43')

  return CryptoJS.AES.encrypt(new Date().getTime().toString(), key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  }).toString()
}
/**
  * 功能：过滤标签
*/
export function filterTag (text) {
  if (text) {
    var reg = /<[^<>]+>/g// 1、全局匹配g肯定忘记写,2、<>标签中不能包含标签实现过滤HTML标签
    text = text.replace(reg, '')// 替换HTML标签
    text = text.replace(/&nbsp;/ig, '')// 替换HTML空格
    return text
  } else {
    return ''
  }
}
